import 'dart:io';

import 'package:cunyutech_flutter_ui/src/dialog/main.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

typedef PayDelegateFunction(String referer, String payUrl);

class H5PayController {
  PayDelegateFunction pay;
}

class H5PayWebView extends StatefulWidget {
  H5PayWebView({
    Key key, 
    this.controller,
  }) : super(key: key);

  final H5PayController controller;

  _H5PayWebViewState createState() => _H5PayWebViewState();
}

class _H5PayWebViewState extends State<H5PayWebView> {
  WebViewController webViewController;
  String referer = "";
  pay(String _referer, String payUrl) {
    referer = _referer;
    webViewController.loadUrl(payUrl, headers: {
      "Referer": referer,
    });
  }

  @override
  Widget build(BuildContext context) {
    return WebView(
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController web) {
        webViewController = web;
        widget.controller.pay = pay;
      },
      navigationDelegate: (NavigationRequest request) {
        print(request.url);
        if(request.url.startsWith("weixin:")) {
          (() async {
            bool isSuccess = await launch(request.url, headers: {
              "Referer": referer,
            });
            if(isSuccess == false)  {
              showToast(msg: "微信调取失败，请重新调取");
            }
          })();
          return NavigationDecision.prevent;
        }

        (() async {
          if(request.url != await webViewController.currentUrl()) {
            webViewController.loadUrl(request.url, headers: {
              "Referer": referer,
            });
          }
          return NavigationDecision.prevent;
        })();
        if(Platform.isIOS) {
          return NavigationDecision.navigate;
        }
        return NavigationDecision.prevent;
      },
    );
  }
}

